﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace Utils.Pool
{
    /// <summary>
    /// 连接池
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Pools<T> where T : IDisposable
    {
        private readonly Queue<T> queue = new Queue<T>();

        /// <summary>
        /// 最大连接数
        /// </summary>
        private readonly int maxPoolSize;

        private readonly int minPoolSize;

        private readonly int millisecondsTimeout;

        private int _currentConnection = 0;

        public Pools(int maxPoolSize = 10, int minPoolSize = 3, int millisecondsTimeout = 2000)
        {
            this.maxPoolSize = maxPoolSize;
            this.minPoolSize = minPoolSize;
            this.millisecondsTimeout = millisecondsTimeout;
        }


        public T CreateOrGet(Func<Task<T>> createConnection)
        {
            lock (this)
            {
                if (queue.Count > 0)
                {
                    return queue.Dequeue();
                }
                if (_currentConnection < maxPoolSize)
                {
                    T connection = createConnection().GetAwaiter().GetResult();
                    _currentConnection++;
                    return connection;
                }
                if (SpinWait.SpinUntil(() => queue.Count > 0, millisecondsTimeout))
                {
                    return queue.Dequeue();
                }
            }
            throw new TimeoutException("GetPool");
        }


        public T CreateOrGet(Func<T> createConnection)
        {
            lock (this)
            {
                if (queue.Count > 0)
                {
                    return queue.Dequeue();
                }
                if (_currentConnection < maxPoolSize)
                {
                    T connection = createConnection();
                    _currentConnection++;
                    return connection;
                }
                if (SpinWait.SpinUntil(() => queue.Count > 0, millisecondsTimeout))
                {
                    return queue.Dequeue();
                }
            }
            throw new TimeoutException("GetPool");
        }

        /// <summary>
        /// 返还到池中
        /// </summary>
        /// <param name="connection"></param>
        public void BackInPools(T connection)
        {
            if (_currentConnection <= minPoolSize)
            {
                queue.Enqueue(connection);
            }
            else
            {
                Dispose(connection);
            }

        }

        public void Dispose(T connection)
        {
            _currentConnection--;
            connection.Dispose();
        }

    }

}
